package com.itchu.auth.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itchu.auth.config.JwtProperties;
import com.itchu.common.utils.CookieUtils;
import com.itchu.common.utils.JwtUtils;
import com.itchu.system.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtProperties prop;

    // 生成cookie
    private void createAndSendTokenToCookie(HttpServletResponse response , SysUser userInfo) {
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, prop.getPrivateKey(), prop.getUser().getExpire());
        CookieUtils.newCookieBuilder()
                .response(response)
                .name(prop.getUser().getAuthCookieName())
                .value(token)
                .domain(prop.getUser().getCookieDomain())
                .httpOnly(true)
                .build();
    }
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 从Security的容器里面取，getPrincipal()返回的对象包含认证成功后sysUser对象的全部信息
        SysUser authUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 为了安全起见就把认证后用户的密码不放进jwt的载荷对象
        authUser.setPassword("");
//        // 生成token
//        String token = JwtUtils.generateTokenExpireInMinutes(authUser,prop.getPrivateKey(),prop.getUser().getExpire());
//        // 现在考虑把token放在请求头好还是cookie中
//        // 用户对象里面有权限了，下面也直接可以返回动态菜单
//        // 返回token
//        response.setHeader("Authorization","Bearer"+token);

        // 生成cookie到前端
        createAndSendTokenToCookie(response,authUser);
        try {

            //登录成功時，返回json格式进行提示
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_OK);
            PrintWriter out = response.getWriter();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("code", HttpServletResponse.SC_OK);
            map.put("message", "登陆成功！");
            map.put("userInfo",authUser);
            out.write(new ObjectMapper().writeValueAsString(map));
            out.flush();
            out.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }
}
